The TouchPanel class also includes gesture recognition, which is demonstrated by the XnaTapHello project. The fields of this project are the same as those in XnaTouchHello, but the LoadContent method is a little different:
Example 1. XNA Project: XnaTapHello File: Game1.cs (excerpt)
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice);
segoe36 = this.Content.Load<SpriteFont>("Segoe36"); textSize = segoe36.MeasureString(text); Viewport viewport = this.GraphicsDevice.Viewport; textPosition = new Vector2((viewport.Width - textSize.X) / 2, (viewport.Height - textSize.Y) / 2);
TouchPanel.EnabledGestures = GestureType.Tap; }
|
Notice the final statement. GestureType is an enumeration with members Tap, DoubleTap, Flick, Hold, Pinch, PinchComplete, FreeDrag, HorizontalDrag, VerticalDrag, and DragComplete, defined as bit flags so you can combine the ones you want with the C# bitwise OR operator.
The Update method is very different.
Example 2. XNA Project: XnaTapHello File: Game1.cs (excerpt)
protected override void Update(GameTime gameTime) { // Allows the game to exit if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit();
while (TouchPanel.IsGestureAvailable) { GestureSample gestureSample = TouchPanel.ReadGesture();
if (gestureSample.GestureType == GestureType.Tap) { Vector2 touchPosition = gestureSample.Position;
if (touchPosition.X >= textPosition.X && touchPosition.X < textPosition.X + textSize.X && touchPosition.Y >= textPosition.Y && touchPosition.Y < textPosition.Y + textSize.Y) { textColor = new Color((byte)rand.Next(256), (byte)rand.Next(256), (byte)rand.Next(256)); } else { textColor = Color.White; } } }
base.Update(gameTime); }
|
Although this program is interested in only one type of gesture, the code is rather generalized. If a gesture is available, it is returned from the TouchPanel.ReadGestureGestureSample. Besides the GestureType and Position used here, a Delta property provides movement information in the form of a Vector2 object. For some gestures (such as Pinch), the GestureSample also reports the status of a second touch point with Position2 and Delta2 properties. method as an object of type
The Draw
method is the same as the previous program, but you’ll find that the
program behaves a little differently from the first one: In the first
program, the text changes color when the finger touches the screen; in
the second, the color change occurs when the finger lifts from the
screen. The gesture recognizer needs to wait until that time to
determine what type of gesture it is.